<script setup lang='ts'>
import { appRef } from '@/models/app.ref';
import { Popconfirm,Modal,ModalConfig } from '@arco-design/web-vue';
import { onMounted, ref } from 'vue';
import Sider from '@/components/chat/Sider.vue'
import Interactive from '@/components/chat/Interactive.vue'
import Explanation from '@/components/Explanation.vue'
import { workService } from '@/services/work.service';
import { ChatWorkMenuInfo,ModelApiEnumOption } from '@/models/chat-work';
import { SiderMenuEnum } from '@/models/@types';
import { getCurrentInstance } from 'vue';
import { propsToAttrMap } from '@vue/shared';
import { shareService } from '@/services/share.service';
import { clipboardWriteText } from '@/utils/common.methods';
import { Message } from '@arco-design/web-vue';

const menus = ref([]);
const currMenu = ref({} as ChatWorkMenuInfo);
const apis = ref(true);
onMounted(() => {
  init();
})

function init(): void {
  menus.value = appRef.chatWork.menus;
  currMenu.value = appRef.chatWork?.currMenu;
  apis.value = true;
}

function onAdd(e: { type: SiderMenuEnum, parent?: string }): void {
  const { type, parent } = e
  appRef.chatWork.add(type, parent);
  init();
}

function onItem(uid: string): void {
  console.log('onItem', uid);
  appRef.chatWork.setCurrKey(uid);

  init();
}
function onEdit(param: { uid: string, label: string }): void {
  const { uid, label } = param;
  appRef.chatWork.edit(uid, label);
}

const isSend = ref(false);
const chunk = ref('');
function sendMessage(textarea: string): void {
  isSend.value = true;
  workService.sendstream(textarea, ((data: string) => {
    console.log(appRef.chatWork.currMenu.uid);
    chunk.value = data;
  }),callback)
}

function callback() {
  isSend.value = false;
}

function onRefresh(quote: string): void {
  isSend.value = true;
  workService.refreshSend(quote).then(() => {
    isSend.value = false;
  });
}

//下面代码是分享功能的代码
const popcontent = ref('');
const popvisible = ref(false);
const poptitle = ref("分享成功")
const checkboxes = ref([]);
const visible = ref(false);
const btnloading = ref(false);
const handleClick = () => {
  visible.value = true;
  checkboxes.value = appRef.chatWork.currMenu.sessions.map(() => false);
};
async function handleBeforeOk() {
  btnloading.value = true;
  const records = appRef.chatWork.currMenu.sessions.filter((_, index) => checkboxes.value[index]);
  if (records != null && records.length > 0) {
    var response = await shareService.send(records);
    if (response.status == true){
      popcontent.value = window.location.href.replace("working-edition", "share") + '/' + response.uuid;
      popvisible.value = true;
      poptitle.value = "分享成功";
      visible.value = false;
      btnloading.value = false;
    }
    else {
      popcontent.value = response.error;
      popvisible.value = true;
      poptitle.value = "分享失败";
      visible.value = false;
      btnloading.value = false;
    }
  }
};
const popBeforeOk = (done) => {
  clipboardWriteText(popcontent.value).then(() => {
    Message.success('复制成功')
  })
  done();
};
const handleCancel = () => {
  visible.value = false;
}
// 复选框状态变化时触发
const handleCheckboxChange = (index) => {
  checkboxes.value[index] = !checkboxes.value[index];
};
function checkAll() {// 检查是否所有值都为true
  const allTrue = checkboxes.value.every(value => value === true);
  console.log(allTrue)

  // 遍历checkboxes中的值，根据条件进行更改
  checkboxes.value = checkboxes.value.map(() => allTrue ? false : true);
}

</script>
<template>
  <div class="index">
    <a-layout style="height: 100%;">
      <Sider :menus="menus" :default-uid="currMenu?.uid" @add="onAdd" @clear="() => { appRef.chatWork.clear(); init() }"
        @click-item="onItem" @edit="($event) => { onEdit($event); init() }"
        @remove="($event) => { appRef.chatWork.remove($event); init() }" />
      <a-layout>
        <div class="main flex-c" v-if="currMenu?.uid">
          <Interactive :chunk="chunk" :sessions="currMenu.sessions" v-if="currMenu?.uid" v-model:isSend="isSend" :isrefresh="true"
            @send="sendMessage" @refresh="onRefresh" @remove="appRef.chatWork.removeMenuAnswer($event)">
            <template #select-model>
              <a-select v-model="currMenu.modelapi" style="width:230px" placeholder="请选择模型">
                <a-option v-for="item in ModelApiEnumOption" :value="item.key" :label="item.name"></a-option>
              </a-select>
              <a-button type="primary" style="margin-left:20px" @click="handleClick">分享聊天记录</a-button>
            </template>
          </Interactive>
        </div>
        <Explanation v-else />
      </a-layout>
    </a-layout>
    <a-modal v-model:visible="visible" title="分享" @cancel="handleCancel" @before-ok="handleBeforeOk">
      <div style="max-height:400px;">
        <a-list>      
          <a-list-item v-for="(item,index) in appRef.chatWork.currMenu.sessions" :key="item.uid"><a-checkbox :model-value="checkboxes[index]" :value="checkboxes[index]" @change="handleCheckboxChange(index)">{{ item.richtext.length > 25 ? `${item.richtext.slice(0, 27)}...` : item.richtext }}</a-checkbox></a-list-item>
        </a-list>
      </div>  
      <template #footer>
        <a-button type="dashed" @click="handleCancel">取消</a-button>
        <a-button type="outline" @click="checkAll">全选</a-button>
        <a-button type="primary" @click="handleBeforeOk" :loading="btnloading">确定</a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="popvisible" :title="poptitle" okText="复制" @cancel="handleCancel" @before-ok="popBeforeOk">
      {{ popcontent }}
    </a-modal>
  </div>
</template>
<style lang='scss' scoped>
.index {
  height: 100%;

  .main {
    justify-content: center;
  }
}
</style>